"""
缓存管理器模块
用于缓存API响应和其他数据
"""

import os
import time
import json
import hashlib
import logging
from typing import Any, Optional

from .config import ensure_dir

logger = logging.getLogger(__name__)

class CacheManager:
    """缓存管理器，用于缓存API响应和其他数据"""
    
    def __init__(self, cache_dir: str, max_age: int = 3600):
        """
        初始化缓存管理器
        
        Args:
            cache_dir: 缓存目录
            max_age: 缓存最大有效期（秒）
        """
        self.cache_dir = cache_dir
        self.max_age = max_age
        ensure_dir(cache_dir)
    
    def _get_cache_path(self, key: str) -> str:
        """
        获取缓存文件路径
        
        Args:
            key: 缓存键
            
        Returns:
            缓存文件路径
        """
        # 使用MD5哈希作为文件名，避免文件名过长或包含非法字符
        hashed_key = hashlib.md5(key.encode()).hexdigest()
        return os.path.join(self.cache_dir, f"{hashed_key}.json")
    
    def get(self, key: str) -> Optional[Any]:
        """
        获取缓存数据
        
        Args:
            key: 缓存键
            
        Returns:
            缓存数据，如果不存在或已过期则返回None
        """
        cache_path = self._get_cache_path(key)
        
        if not os.path.exists(cache_path):
            return None
        
        try:
            # 检查文件修改时间
            mtime = os.path.getmtime(cache_path)
            if time.time() - mtime > self.max_age:
                # 缓存已过期
                return None
            
            with open(cache_path, 'r') as f:
                cache_data = json.load(f)
                return cache_data.get("data")
        except Exception as e:
            logger.warning(f"读取缓存失败: {e}")
            return None
    
    def set(self, key: str, data: Any) -> bool:
        """
        设置缓存数据
        
        Args:
            key: 缓存键
            data: 要缓存的数据
            
        Returns:
            是否成功
        """
        cache_path = self._get_cache_path(key)
        
        try:
            with open(cache_path, 'w') as f:
                cache_data = {
                    "timestamp": time.time(),
                    "data": data
                }
                json.dump(cache_data, f)
            return True
        except Exception as e:
            logger.warning(f"写入缓存失败: {e}")
            return False
    
    def clear(self, max_age: Optional[int] = None) -> int:
        """
        清除过期缓存
        
        Args:
            max_age: 最大有效期（秒），如果为None则使用默认值
            
        Returns:
            清除的文件数量
        """
        if max_age is None:
            max_age = self.max_age
        
        count = 0
        now = time.time()
        
        for filename in os.listdir(self.cache_dir):
            file_path = os.path.join(self.cache_dir, filename)
            
            if os.path.isfile(file_path) and filename.endswith(".json"):
                mtime = os.path.getmtime(file_path)
                if now - mtime > max_age:
                    try:
                        os.remove(file_path)
                        count += 1
                    except Exception as e:
                        logger.warning(f"删除缓存文件失败: {e}")
        
        return count